package com.bjpowernode.boss.exception;

import com.bjpowernode.boss.enums.ajax.Code;
import com.bjpowernode.boss.mvc.model.result.AjaxResult;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import java.util.List;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalBossExceptionHandler {

    @ExceptionHandler({BossException.class})
    public AjaxResult handleException(BossException e){
        e.printStackTrace();
        Code code = e.getCode();
        return AjaxResult
                .builder()
                .code(code.getCode())
                .msg(code.getMsg())
                .build();
    }


    @ExceptionHandler({BindException.class})
    public AjaxResult handleException(BindException e) {
        e.printStackTrace();  // 打印错误日志
        StringBuilder builder = new StringBuilder();
        List<FieldError> fieldErrors = e.getFieldErrors(); // 获取错误字段
        // 遍历格式化
        for (FieldError fieldError : fieldErrors) {
            builder.append("输入项:[")
                    .append(fieldError.getField())
                    .append("],错误值[")
                    .append(fieldError.getDefaultMessage())
                    .append("]");
        }
        return AjaxResult
                .builder()
                .code(Code.REQUEST_PARAM_ERR.getCode())
                .msg(Code.REQUEST_PARAM_ERR.getMsg() + " : " + builder)
                .build();
    }
}
